// 初始化确认
console.log('搜索高亮工具: Content Script 已加载');

let lastHighlightedElements = [];

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
  console.log('搜索高亮工具: 收到消息', request);
  
  if (request.action === 'highlight') {
    // 清除之前的高亮
    clearHighlights();
    
    // 执行新的搜索和高亮
    highlightText(request.searchText);
    
    // 发送响应
    sendResponse({success: true});
  }
  
  // 必须返回true以支持异步sendResponse
  return true;
});

function clearHighlights() {
  console.log('搜索高亮工具: 清除之前的高亮');
  lastHighlightedElements.forEach(el => {
    const parent = el.parentNode;
    if (parent) {
      parent.replaceChild(el.firstChild, el);
    }
  });
  lastHighlightedElements = [];
}

function highlightText(searchText) {
  console.log('搜索高亮工具: 开始搜索', searchText);
  const searchRegex = new RegExp(escapeRegExp(searchText), 'gi');
  const walker = document.createTreeWalker(
    document.body,
    NodeFilter.SHOW_TEXT,
    null,
    false
  );

  let node;
  let matchCount = 0;
  while (node = walker.nextNode()) {
    const parent = node.parentNode;
    if (parent.nodeName !== 'SCRIPT' && 
        parent.nodeName !== 'STYLE' && 
        parent.nodeName !== 'MARK') {
      const content = node.textContent;
      if (searchRegex.test(content)) {
        const highlightedContent = content.replace(
          searchRegex,
          match => `<mark class="extension-highlight">${match}</mark>`
        );
        const span = document.createElement('span');
        span.innerHTML = highlightedContent;
        parent.replaceChild(span, node);
        
        // 保存高亮的元素，以便后续清除
        const marks = span.getElementsByTagName('mark');
        lastHighlightedElements.push(...marks);
        matchCount += marks.length;
      }
    }
  }
  
  console.log('搜索高亮工具: 找到匹配项数量', matchCount);
  
  // 如果找到匹配项，滚动到第一个高亮处
  if (lastHighlightedElements.length > 0) {
    lastHighlightedElements[0].scrollIntoView({
      behavior: 'smooth',
      block: 'center'
    });
  }
}

function escapeRegExp(string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
} 